import streamlit as st
import database as db
import time

def init_auth():
    """初始化认证相关的session状态"""
    if 'logged_in' not in st.session_state:
        st.session_state.logged_in = False
    if 'user' not in st.session_state:
        st.session_state.user = None
    if 'login_error' not in st.session_state:
        st.session_state.login_error = False

def login_page():
    """渲染登录页面"""
    st.title("行人轨迹跟踪与分析系统")
    
    if st.session_state.login_error:
        st.error("用户名或密码错误")
        st.session_state.login_error = False
    
    with st.form("login_form"):
        username = st.text_input("用户名")
        password = st.text_input("密码", type="password")
        submit = st.form_submit_button("登录")
        
        if submit:
            user = db.authenticate_user(username, password)
            if user:
                st.session_state.logged_in = True
                st.session_state.user = user
                st.rerun()
            else:
                st.session_state.login_error = True
                st.rerun()
    
    st.markdown("---")
    st.markdown("默认账户：")
    st.markdown("- 管理员：admin/admin")
    st.markdown("- 普通用户：user/user")

def logout():
    """用户登出"""
    st.session_state.logged_in = False
    st.session_state.user = None

def is_admin():
    """检查当前用户是否为管理员"""
    if not st.session_state.logged_in or not st.session_state.user:
        return False
    return st.session_state.user.get('is_admin', False)

def require_login(func):
    """装饰器：要求用户登录"""
    def wrapper(*args, **kwargs):
        if not st.session_state.logged_in:
            login_page()
            return
        return func(*args, **kwargs)
    return wrapper

def require_admin(func):
    """装饰器：要求管理员权限"""
    def wrapper(*args, **kwargs):
        if not st.session_state.logged_in:
            login_page()
            return
        if not is_admin():
            st.error("需要管理员权限")
            time.sleep(2)
            st.rerun()
            return
        return func(*args, **kwargs)
    return wrapper

def manage_users():
    """用户管理界面"""
    st.title("用户管理")
    
    users = db.get_all_users()
    
    # 添加新用户部分
    st.subheader("添加新用户")
    with st.form("add_user_form"):
        new_username = st.text_input("用户名")
        new_password = st.text_input("密码", type="password")
        is_admin = st.checkbox("管理员权限")
        submit = st.form_submit_button("添加用户")
        
        if submit:
            if new_username and new_password:
                success = db.add_user(new_username, new_password, is_admin)
                if success:
                    st.success(f"用户 {new_username} 添加成功")
                    time.sleep(1)
                    st.rerun()
                else:
                    st.error(f"添加用户失败，用户名 {new_username} 可能已存在")
            else:
                st.warning("用户名和密码不能为空")
    
    # 显示用户列表
    st.subheader("用户列表")
    if not users:
        st.info("暂无用户")
        return
    
    for user in users:
        col1, col2, col3, col4 = st.columns([2, 2, 1, 1])
        
        with col1:
            st.write(f"**{user['username']}**")
        
        with col2:
            role = "管理员" if user['is_admin'] else "普通用户"
            st.write(role)
        
        with col3:
            if st.button("编辑", key=f"edit_{user['id']}"):
                st.session_state.edit_user_id = user['id']
                st.session_state.edit_username = user['username']
                st.session_state.edit_is_admin = user['is_admin']
                st.rerun()
        
        with col4:
            if user['id'] != st.session_state.user['id']:  # 不能删除自己
                if st.button("删除", key=f"delete_{user['id']}"):
                    if db.delete_user(user['id']):
                        st.success(f"用户 {user['username']} 已删除")
                        time.sleep(1)
                        st.rerun()
                    else:
                        st.error("删除用户失败")
            else:
                st.write("当前用户")
    
    # 编辑用户表单
    if 'edit_user_id' in st.session_state:
        st.subheader("编辑用户")
        with st.form("edit_user_form"):
            edit_username = st.text_input("用户名", value=st.session_state.edit_username)
            edit_password = st.text_input("密码 (留空保持不变)", type="password")
            edit_is_admin = st.checkbox("管理员权限", value=st.session_state.edit_is_admin)
            
            col1, col2 = st.columns(2)
            with col1:
                submit = st.form_submit_button("保存")
            with col2:
                cancel = st.form_submit_button("取消")
            
            if submit:
                success = db.update_user(
                    st.session_state.edit_user_id,
                    new_username=edit_username if edit_username != st.session_state.edit_username else None,
                    new_password=edit_password if edit_password else None,
                    is_admin=edit_is_admin
                )
                
                if success:
                    st.success("用户信息已更新")
                    # 如果修改的是当前用户，更新session状态
                    if st.session_state.edit_user_id == st.session_state.user['id']:
                        st.session_state.user['username'] = edit_username
                        st.session_state.user['is_admin'] = edit_is_admin
                    
                    del st.session_state.edit_user_id
                    del st.session_state.edit_username
                    del st.session_state.edit_is_admin
                    time.sleep(1)
                    st.rerun()
                else:
                    st.error("更新用户信息失败")
            
            if cancel:
                del st.session_state.edit_user_id
                del st.session_state.edit_username
                del st.session_state.edit_is_admin
                st.rerun() 